<?php namespace App\Admin\Goods\Goods;

//基础条件
use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Repository\Criterias\PaginateCriteria;
use App\Core\Repository\Criterias\SortCriteria;
//过滤器
use App\Core\Repository\Criterias\Filters\InputCriteria;
use App\Core\Repository\Criterias\Filters\InputKeywordsCriteria;
use App\Core\Repository\Criterias\Filters\InputTimeRangeCriteria;

use Input;
use DB;
require_once app_path().'/Library/excel/PHPExcel.php';
use App\Admin\Supplier\Supplier\Repository as SupplierRepository;
use App\Admin\Goods\Brand\Repository as BrandRepository;


trait Service {
    
    //基础服务
    use \App\Core\Service\Service;
    use \App\Core\Service\Services\All;
    use \App\Core\Service\Services\Indexer;
    use \App\Core\Service\Services\Creater;
    use \App\Core\Service\Services\Updater;
    use \App\Core\Service\Services\Changer;
    use \App\Core\Service\Services\Deleter;
    use \App\Core\Service\Services\Detailer;
    use \App\Core\Service\Services\Sorter;
    //操作日志
    use \App\Admin\Base\LogService;
    
    protected function bootService(){
        $this->bootBaseService();
        $this->setRepository(new Repository);
        $this->setMeta(new Meta);
        $this->repository = $this->getRepository();
    }
	
    //列表
    public function lists(){
        //过滤器
        $conditions = [
            new InputKeywordsCriteria('name,classify'),
            new InputTimeRangeCriteria('created_at'),
            new InputCriteria('is_experience'),
            new InputCriteria('status')
        ];
        $count = $this->repository->addCriterias($conditions)->count();
        $conditions[] = new PaginateCriteria();
        $conditions[] = new SortCriteria('sort', 'ASC');
        $conditions[] = new SortCriteria('status', 'DESC');
        $conditions[] = new SortCriteria('id', 'DESC');
        $data = $this->repository->resetQuery()->resetCriteria()->addCriterias($conditions)->all();
        $data->load('brand','supplier');
        return $this->success([
            'count' => $count,
            'data' => $data
        ]);
    }

    //新列表
    public function newlists(){
        //过滤器
        $status = 1;
        $conditions = [
            new InputKeywordsCriteria('name'),
            new FixedCriteria('status', $status)
        ];
        $count = $this->repository->addCriterias($conditions)->count();
        $conditions[] = new SortCriteria('id', 'DESC');
        $data = $this->repository->resetQuery()->resetCriteria()->addCriterias($conditions)->all();
        return $this->success([
            'count' => $count,
            'data' => $data
        ]);
    }

    //排序
    public function sort(){
        $this->initSorter([
            'attrs'=>['status']
        ]);
        return $this->applySort();
    }
    
    //上线
    public function online(){
        return $this->change('status', '1', '0');
    }
    
    //下线
    public function offline(){
        return $this->change('status', '0', '1');
    }
    
    //批量上线
    public function multiOnline(){
        return $this->multiChange('status', '1', '0');
    }
    
    //批量下线
    public function multiOffline(){
        return $this->multiChange('status', '0', '1');
    }


    public function multiExport(){
        $name = Input::get('keywords');
        $begin_time = strtotime(Input::get('begin_time'));
        $end_time = strtotime(Input::get('end_time'));
        $status = Input::get('status');
        $experience = Input::get('is_experience');

        $curTime = time();

        $goods = DB::table('goods');
        if($begin_time > 0 && $curTime > $begin_time){
            $goods->where('created_at','>',$begin_time);
        }
        if($end_time > 0 && $curTime > $end_time){
            $goods->where('created_at','<',$end_time+24*3600);
        }
        if($name){
            $goods->where('name','like','%'.$name.'%');
        }
        if($experience){
            $goods->where('is_experience','=',$experience);
        }
        if($status){
            $goods->where('status','=',$status);
        }

        $goods = $goods->where('is_delete','=',0)
            ->orderBy('id','desc')
            ->get();
        foreach($goods as $v){
            if(!$v){
                continue;
            }
            //供应商
            $supplier_id = $v->supplier_id;
            if($supplier_id != 0){
                $supplier = with(new SupplierRepository)->addCriteria(new FixedCriteria('id', $supplier_id))->first();
                $v->supplier_id = $supplier->name;
            }else{
                $v->supplier_id = '暂无';
            }
            //品牌
            $brand_id = $v->brand_id;
            if($brand_id != 0){
                $brand = with(new BrandRepository)->addCriteria(new FixedCriteria('id', $brand_id))->first();
                $v->brand_id = $brand->name;
            }else{
                $v->brand_id = '暂无';
            }
            //上架时间
            $created_at = $v->created_at;
            if($created_at!=null){
                $v->created_at = date("Y-m-d H:i:s",$created_at);
            }
        }

        //实例化
        $objPHPExcel = new \PHPExcel();
        /*右键属性所显示的信息*/
        $objPHPExcel->getProperties()->setCreator("csk")  //作者
        ->setLastModifiedBy("csk")  //最后一次保存者
        ->setTitle('商品列表导出')  //标题
        ->setSubject('商品列表导出') //主题
        ->setDescription('导出数据')  //描述
        ->setKeywords("excel")   //标记
        ->setCategory("result file");  //类别

        //设置当前的表格
        $objPHPExcel->setActiveSheetIndex(0);

        if($name == null){
            $name = '所有商品';
        }else{
            $name = '关于'.$name.'的商品';
        }

        if($status == null){
            $status = '全部上下线的';
        }else if($status == 0){
            $status = '下线的';
        }else if($status == 1){
            $status = '在线的';
        }

        if($experience == null){
            $experience = '可以和不可以体验的';
        }else if($experience == 0){
            $experience = '可体验的';
        }else if($experience == 1){
            $experience = '不可体验的';
        }

        $pre = '';
        if($_GET['begin_time'] && $_GET['end_time']){
            $pre = $_GET['begin_time'].'到'.$_GET['end_time'].'上架-';
        }else if(!$_GET['begin_time'] && !$_GET['end_time']){
            $pre = '全部上架时间-';
        }else if($_GET['begin_time'] && !$_GET['end_time']){
            $pre = $_GET['begin_time'].'之后上架-';
        }else if(!$_GET['begin_time'] && $_GET['end_time']){
            $pre = $_GET['end_time'].'之前上架-';
        }

        $filename = $pre.$status.'商品.xls';
        $title = $pre.$experience.$status.$name;

        //处理表头标题
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//垂直居中
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
        $objPHPExcel->getActiveSheet()->mergeCells('A1:O1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1',$title);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);//加粗

        // 设置表格第二行显示内容
        $objPHPExcel->getActiveSheet()
            ->setCellValue('A2', '序号')
            ->setCellValue('B2', '商品名')
            ->setCellValue('C2', '进货价')
            ->setCellValue('D2', '限价')
            ->setCellValue('E2', '商城价')
            ->setCellValue('F2', '走路抵金')
            ->setCellValue('G2', '体验价')
            ->setCellValue('H2', '体验抵金')
            ->setCellValue('I2', '供应商')
            ->setCellValue('J2', '品牌名')
            ->setCellValue('K2', '型号')
            ->setCellValue('L2', '库存')
            ->setCellValue('M2', '卖出数量')
            ->setCellValue('N2', '关键词')
            ->setCellValue('O2', '上架时间');

        $key = 2;
        foreach($goods as $v){
            //设置循环从第三行开始
            $key++;
            $objPHPExcel->getActiveSheet()
                //Excel的第A列，name是你查出数组的键值字段，下面以此类推
                ->setCellValue('A'.$key, $v->id)
                ->setCellValue('B'.$key, $v->name)
                ->setCellValue('C'.$key, $v->price_cost)
                ->setCellValue('D'.$key, $v->fixed_price)
                ->setCellValue('E'.$key, $v->price_original)
                ->setCellValue('F'.$key, $v->moneylimit)
                ->setCellValue('G'.$key, $v->price_lowest)
                ->setCellValue('H'.$key, $v->experience_payment)
                ->setCellValue('I'.$key, $v->supplier_id)
                ->setCellValue('J'.$key, $v->brand_id)
                ->setCellValue('K'.$key, $v->models)
                ->setCellValue('L'.$key, $v->inventory)
                ->setCellValue('M'.$key, $v->sell_total)
                ->setCellValue('N'.$key, $v->classify)
                ->setCellValue('O'.$key, $v->created_at);
        }

        //设置当前的表格
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel'); //文件类型
        header('Content-Disposition: attachment;filename='.$filename.''); //文件名
        header('Cache-Control: max-age=0');
        header('Content-Type: text/html; charset=utf-8'); //编码
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        ob_start();
        $objWriter->save('php://output');
        $xlsData = ob_get_contents();
        ob_end_clean();

        return $this->success([
            'filename' => $filename,
            'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
        ]);

    }


}